#!/usr/bin/env python
# -*- coding: utf-8 -*-

#
# This program is free software; you can redistribute it and/or modify  
# it under the terms of the GNU General Public License as published by  
# the Free Software Foundation; either version 2 of the License, or     
# (at your option) any later version.                                   
#                                                                         
# A copy of the license can be found in the license.txt file supplied   
# with this software or at: http://www.gnu.org/copyleft/gpl.html       
#

# 
#  Data Transfer Stack :
#  codec    : None
#  protocol : TextSizeProtocol
#

import sys

from spinage.mpserver import Server
from spinage.help.protocol.simpletextsize import SimpleTextSizeProtocolFactory

from spinage.help.zipcodecor import ZipCodecor
from spinage.help.base64codecor import Base64Codecor
from spinage.help.passthrucodecor import PassthruCodecor

from spinage.help.router import RoundRobinRouter

from spinage.help import logging

PORT = 4344

#logging.getLogger().setLevel(logging.LEVEL_DEBUG)

class   EchoHandler(object) :
    def handle(self, data, session) :
        return data,session
        ## handle()
    ## class EchoHandler


if __name__ == '__main__' :

    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option("", "--codec", dest="codec", type="string", default='',
                        help='codecors, none or more, separated by ","; e.g. "zip", "zip,base64","json","base64"')
    parser.add_option("-p", "--protocol", dest="protocol", type="string", default='textsize',
                        help='communcation protocol, such as "textsize" (default), "textline"')

    parser.add_option("-l", "--logconf", dest="logconfig", type="string",
                        help='path to logging configure file')

    parser.add_option("-d", "--debug", dest="debug", action="store_true", default=False,
                        help='show debug information')

    (options, args) = parser.parse_args()
    if not options.protocol :
        parser.print_help( sys.stdout )
        sys.exit(0)

    if options.logconfig :
        logging.loadConfigure( options.logconfig )

    if options.debug :
        logger = logging.getLogger()
        logger.setLevel(logging.LEVEL_DEBUG)

    ####-----------------------------------------------------------####

    if 'textsize' == options.protocol :
        protocol_factory = SimpleTextSizeProtocolFactory()
    elif 'textline' == options.protocol :
        protocol_factory = SimpleTextLineProtocolFactory()
    else :
        raise RuntimeError,'Unsupport protocol "%s"' % options.protocol

    codecor_list = []
    if options.codec :
        codecor_names = options.codec.split(',')
        for name in codecor_names :
            if 'zip' == name :
                codecor = ZipCodecor()
            elif 'base64' == name :
                codecor = Base64Codecor()
            elif 'passthru' == name :
                codecor = PassthruCodecor()
            else :
                raise RuntimeError, 'Unsupport codecor "%s"' % name
            codecor_list.append( codecor )

    logger = logging.getLogger('EchoServer')

    s = Server()

    s.setProtocolFactory( protocol_factory )

    if codecor_list :
        codec_chain = s.getCodecChain()
        for codecor in codecor_list :
            codec_chain.add( codecor )

    logger.info(' listening TCP port %d ...', PORT)
    s.listen( PORT )

    handler = EchoHandler()
    s.setHandler( handler )
    s.setHandler( handler )
    s.setHandler( handler )

    router = RoundRobinRouter()
    s.setRouter( router )

    try :
        s.serve_forever()
    except KeyboardInterrupt :
        pass

    sys.exit(0)


